<?
/**
 *订单记录类.
 *查询订单详情和处理订单的相关操作.
 */
class OrderRecord{
	/**
	 *订单号.
	 *var int 
	 */
	private $ordernum;
	
	/**
	 *票付通内部接口对象
	 *@var object
	 */
	private $s;
	
	/**
	 *键值数组对应UUstatus文本和样式
	 *@static
	 *@var array 
	 */
	public static $UUstatusT=array(0=>"未使用",1=>"<em class='green'>已使用</em>",2=>"已过期",3=>"<em class='red'>已取消</em>",4=>"被替代",5=>"被修改",6=>"已撤销",7=>"部分使用");
	
	/**
	 *键值数组对应UUstatus文本和样式
	 *@static
	 *@var array 
	 */
	public static $statusT=array("0"=>"未使用","1"=>"<em class='green'>已使用</em>","2"=>"<em class='gray'>已过期</em>","3"=>"<em class='red'>已取消</em>","4"=>"凭证码被替代","6"=>"被终端撤销</br><em class='red'>(已取消)</em>","5"=>"被终端修改</br><em class='green'>(已使用)</em>");
	public static $_nSStatusT=array("0"=>"未使用","1"=>"已使用","2"=>"已过期","3"=>"已取消","4"=>"凭证码被替代","6"=>"被终端撤销</br>(已取消)","5"=>"被终端修改----(已使用)");
	
	/**
	 *键值数组对应UUpmode文本和样式
	 *@static
	 *@var array 
	 */
	public static $paymodeT=array(0=>"账户余额",1=>"支付宝",2=>"授信支付",3=>"产品自销",4=>"现场支付");
	
	/**
	 *键值数组对应UUpaystatus文本和样式
	 *@static
	 *@var array 
	 */
	public static $paystatusT=array(1=>"<em class='green'>(已支付)</em>",2=>"<em class='orange'>(待支付)</em>");
	
	/**
	 *键值数组对应门票产品类型
	 *@static
	 *@var array 
	 */
	public static $p_typeT=array("A"=>"门票","B"=>"线路","C"=>"酒店","D"=>"商品","F"=>"套票");
	
	/**
	 *构造函数.
	 *@param int $ordernum 订单号
	 *@param object 票付通内部接口对象
	 */
	public function __construct($ordernum,$s){
		$this->ordernum=$ordernum;
		$this->s=$s;
	}
	
	/**
	 *格式化订单记录函数.
	 *联票订单将以存在主订单和从订单，非联票订单制存在主订单
	 *@param object simplexml对象
	 *@return array
	 */
	public static function format($simxml){

        $info=array();
        $info['childOrder']=array();
        $info['orderAlipay']=false;
        $info['orderCancel']=false;
        $info['orderAlter'] =false;
        $count=count($simxml);
        foreach($simxml as $row){
            if($count>1){
                if((string)$row->UUconcat_id===(string)$row->UUordernum){
                    $info['mainOrder'] = $row;
                }else{
                    $info['childOrder'][]=$row;
                }
            }
            else{
                $info['mainOrder']=$row;
            }
            $info['totalPrice'] +=(string)$row->UUtotalmoney;
            $info['totalTnum']  +=(string)$row->UUtnum;
            $info['totalOrder']++;
        }
        if($info['mainOrder']->UUpmode==1&&$info['mainOrder']->UUpaystatus!=1 && $info['mainOrder']->UUstatus==0 && (string)$info['mainOrder']->UUbuyid==$_SESSION['sid']){
            $info['orderAlipay']=true;
        }

        if($info['mainOrder']->UUremotenum==0&&(string)$info['mainOrder']->UUpaystatus==1){
            if(in_array((string)$info['mainOrder']->UUstatus,array(0)) && (string)$info['mainOrder']->UUbuyid==$_SESSION['sid']){// 只有购买的人才有权限修改
                $info['orderAlter']=true;
                $info['orderResend']=true;
            }
            if(in_array((string)$info['mainOrder']->UUstatus,array(0,2)) && (string)$info['mainOrder']->UUbuyid==$_SESSION['sid']){
                $info['orderCancel']=true;
            }
        }
        if((string)$info['mainOrder']->UUpaystatus==2 && (string)$info['mainOrder']->UUstatus==0 && (string)$info['mainOrder']->UUbuyid==$_SESSION['sid']){
            $info['orderCancel']=true;
        }

        
        // 现场支付
        if((int)$info['mainOrder']->UUpmode==4 && (int)$info['mainOrder']->UUstatus==0){
            $info['orderAlter'] =1;
            $info['orderCancel']=1;
            $info['orderResend']=1;
        }
        // exit;
        // 散客支付
        if((string)$info['mainOrder']->UUcontacttel==$_SESSION['account'] && $info['mainOrder']->UUpmode==1&&$info['mainOrder']->UUpaystatus!=1 && $info['mainOrder']->UUstatus==0){
            // echo $info['mainOrder']->UUordernum;
            // exit;
            $info['orderAlipay']=true;
        }
        // print_r($info['mainOrder']);
        return $info;
    }

	/**
	 *格式化订单记录函数.
	 *联票订单将以存在主订单和从订单，非联票订单制存在主订单
	 *@param object simplexml对象
	 *@return array
	 *说明：童改写，解决订单号查询时没有从订单。不改变源码做冗余；
	 */
	public static function _format($simxml,$other){
		$info=array();
		$info['childOrder']=array();
		$info['orderAlipay']=false;
		$info['orderCancel']=false;
		$info['orderAlter']=false;
		$count=count($simxml);
		// echo $count;
		// print_r($other);
		// exit;
		foreach($simxml as $row){
			if($count>1){
				if($row->UUifpack>0){
					if($row->UUifpack==1){
						$info['mainOrder']=$row;
					}else{
						$info['packOrder'][]=$row;
						continue;
					}
				}else{
					if($row->UUconcat_id=="main"){
						$info['mainOrder']=$row;
						
					}else{
						$info['childOrder'][]=$row;
					}
				}
			}else{
				// echo "我来也";
				$info['mainOrder']=$row;
				if(count($other)){
					$info['childOrder'][]=$other;
				}
			}
			$info['totalPrice']+=(string)($row->UUtnum*$row->UUtprice);
			$info['totalTnum']+=(string)$row->UUtnum;
			$info['totalOrder']++;
			if(count($other)){
				$info['totalOrder']+=count($other);
				$info['totalPrice']+=(string)($other->UUtnum*$other->UUtprice);
			}
		}
		if($info['mainOrder']->UUpmode==1&&$info['mainOrder']->UUpaystatus!=1){
			$info['orderAlipay']=true;
		}
		if($info['mainOrder']->UUremotenum==0&&(string)$info['mainOrder']->UUpaystatus==1){
			if(in_array((string)$info['mainOrder']->UUstatus,array(0))){
				$info['orderAlter']=true;
				$info['orderResend']=true;
			}
			if(in_array((string)$info['mainOrder']->UUstatus,array(0,2))){
				$info['orderCancel']=true;
			}
			
		}
		return $info;
	}
	
	/*订单操作（查看，修改，重发，取消,支付）权限*/
	
	/**
	 *订单操作权限查询函数.
	 *查看用户是否有订单操作权限
	 *@param int $order 订单号
	 *@param int $did 操作人ID
	 *@param int $account 普通用户账号，机预订手机号
	 *@param string $auth 需查询权限字段 orderView,orderCancel,orderAlter,orderChange
	 *@return array
	 */
	public static function orderOperAuth($order,$did,$account="",$auth){
		//if($order['mainOrder']->UUordernum=="100476") echo $auth;
		if($auth=="orderView"){
			if($did==(string)$order['mainOrder']->UUmid||$did==(string)$order['mainOrder']->UUaid||$did==1)
			return true;
		}
		if((string)$order['mainOrder']->UUordermode==0&&$order[$auth]){//分销下单权限
			if($did==(string)$order['mainOrder']->UUmid)
					return true;
		}
		if(in_array((string)$order['mainOrder']->UUordermode,array(1,2))&&$order[$auth]){//普通用户下单
			// if($account==(string)$order['mainOrder']->UUordertel)
            if($did==(string)$order['mainOrder']->UUmid)
					return true;
		}
		return false;
	}
	
	/**
	 *查询订单数据.
	 *联票也一同被返回,故有可存在对个simplexml对象
	 *@return object
	 */
	public function info($ifpack=1,$concat_id=0){
        // 
        $buyid = ($_REQUEST['from']=='buy' && $_SESSION['dtype']!=9 && $_SESSION['dtype']!=5) ? $_SESSION['sid']:'';
        $saleid = ($_REQUEST['from']=='sale' && $_SESSION['dtype']!=9 && $_SESSION['dtype']!=5) ? $_SESSION['sid']:'';
		$xml=$this->s->Order_Globle_Search("",$buyid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,99,"","","","","","","","",$saleid,0,1);
		$simxml = simplexml_load_string($xml);
        //TODO::套票订单，查询子订单
        if ($simxml->Rec->UUp_type=='F') {
            $info['mainOrder'] = $simxml->Rec;
            $info['totalPrice'] =$simxml->Rec->UUtotalmoney;
            $info['totalTnum']  =$simxml->Rec->UUtnum;
            $xmlChildOrders = $this->s->Order_Globle_Search("","","","","","", "","","","","","",$this->ordernum,"","","","","",1,1,0,999,"", "","","","","","","","",0,2);
            $simxml2 = simplexml_load_string($xmlChildOrders);
            foreach($simxml2 as $r2) {
                $info['childOrder'][] = $r2;
            }
            return $info;
        }else{  // 如果 UUconcat_id 不为 0 表示复票
            if($simxml->Rec->UUconcat_id!=0){
                $xml=$this->s->Order_Globle_Search("",$buyid,"","","","","","","","","","",$this->ordernum,"","","","","",1,1,0,999,"","","","","","","","",$saleid,1,0);
            }
            $simxml = simplexml_load_string($xml);
        }
        return $this->format($simxml->Rec);
	}
	
	/**
	 *订单取消函数.
	 *联票也一同被返回,故有可存在对个simplexml对象
	 *@return bool 成功返回true
	 */
	public function cancel($operator){
		$orders=$this->info();
		$array=array();
		$array[]=$orders['mainOrder'];
		if($orders['mainOrder']->UUordermode==0){
			if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权取消");
		}else{
			$str="select account from pft_member where id=$operator";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
			// if($operator!=(string)$orders['mainOrder']->UUmid)
				throw new Exception("非游客自身订单，无权取消");
		}
		$array=array_merge($array,$orders['childOrder']);
        // print_r($array);
        // exit;
		foreach($array as $row){
            // echo "Order_Change_Pro(".(string)$row->UUordernum.",0,-1,0,$operator)";
		    $this->s->Order_Change_Pro((string)$row->UUordernum,0,-1,0,$operator);
		}
        // exit;
		return true;
	}
	
	/**
	 *重发短信函数.
	 *@return bool 成功返回true
	 */
	public function resendMsg(){
		$orders=$this->info();
		return $this->s->reSend_SMS_Global_PL((string)$orders['mainOrder']->UUordernum,(string)$orders['mainOrder']->UUaid,(string)$orders['mainOrder']->UUmid);//最后重发短信
	}
	
	/**
	 *修改订单门票数函数.
	 *@param int $tid 门票ID
	 *@param int $tnum 门票数
	 *@param int $operator 操作人ID
	 *@return bool 成功返回true
	 */
	public function changeTnum($tid,$tnum,$operator){
		$orders=$this->info();
		$array=array();
		$array[]=$orders['mainOrder'];
		if($orders['mainOrder']->UUordermode==0){
			if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权修改数量");
		}else{
			$str="select account from pft_member where id=$operator";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
			// if($operator!=(string)$orders['mainOrder']->UUmid)
				throw new Exception("非游客自身订单，无权修改数量");
		}
		$array=array_merge($array,$orders['childOrder']);
		foreach($array as $row){
			if((string)$row->UUtid==$tid&&$tnum<(string)$row->UUtnum){
				$totalprice=(float)$row->UUtprice*$tnum;
				$this->s->Order_Change_Pro((string)$row->UUordernum,$tnum,$totalprice,0,$operator);
			}
		}
		return true;
	}
	
	/**
	 *修改订单游玩时间函数.
	 *@param date $begintime 游玩时间
	 *@param int $operator 操作人ID
	 *@return bool 成功返回true
	 */
	public function changeBegintime($begintime,$operator){
		$orders=$this->info();
		$array[]=$orders['mainOrder'];
		if($orders['mainOrder']->UUordermode==0){
			if($operator!=$orders['mainOrder']->UUmid) throw new Exception("非自身订单，无权修改时间");
		}else{
			$str="select account from pft_member where id=$operator";
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			if($GLOBALS['le']->f("account")!=(string)$orders['mainOrder']->UUordertel)
				throw new Exception("非游客自身订单，无权修改时间");
		}
		$times=strtotime($orders['mainOrder']->UUendtime-$UUbegintime);
		$array=array_merge($array,$orders['childOrder']);
		$endtime=date("Y-m-d H:i:s",strtotime($begintime)+$times);
		foreach($array as $row){
			$this->s->Order_Change_Pro((string)$row->UUordernum,-1,-1,1,$operator,$begintime,$endtime);
		}
		return true;
	}

	
	
    
    /**
	 *未支付订单支付函数.
	 *将处理订单的分润数据，并跳的支付宝支付
	 */
	public function alipay_c(){
        // $host = $_SERVER['HTTP_HOST'];
        $script_uri = substr($_SERVER['SCRIPT_URI'],0,strrpos($_SERVER['SCRIPT_URI'],'/'));       
		$orderInfo=$this->info();
		$orderid=(string)$orderInfo['mainOrder']->UUordernum;
		$title=($orderInfo['mainOrder']->UUltitle).($orderInfo['mainOrder']->UUttitle);
		$money=$orderInfo['totalPrice']/100;
        $lid = (string)$orderInfo['mainOrder']->UUlid;
        $data = array(
            'WIDout_trade_no'=> $orderid ,//商户订单号
            'WIDsubject'=>$title,    // 订单名称
            'WIDtotal_fee'=>$money, // 付款金额
            'WIDshow_url'=>$script_uri.'/gdetail.html?lid='.$lid,  // 商品展示地址
            'WIDbody'=>'会员购买产品'.$title,// 订单描述
            'return_url'=>$script_uri.'/gpay_suc.html',// 支付成功显示页面
            'notify_url'=>$script_uri.'/alipay/ali_order/notify_url_dev.php',// 回调地址
            'buyid'=>(string)$orderInfo['mainOrder']->UUmid // 分销商 ID 
        );
		$this->make_post_c($data);
	}
    
    /**
	 *未支付订单支付函数.
	 *将处理订单的分润数据，并跳的支付宝支付
	 */
	public function alipay_cst($orderid, $title, $money,$mid){
        $script_uri = substr($_SERVER['SCRIPT_URI'],0,strrpos($_SERVER['SCRIPT_URI'],'/'));
        $data = array(
            'WIDout_trade_no'=> $orderid ,//商户订单号
            'WIDsubject'=>$title,    // 订单名称
            'WIDtotal_fee'=>$money, // 付款金额
            'WIDshow_url'=>'',  // 商品展示地址
            'WIDbody'=>$title,// 订单描述
            'return_url'=>$script_uri.'/gpay_suc.html',
            'notify_url'=>$script_uri.'/alipay/ali_order/notify_url_dev.php',// 回调地址
            'buyid'=>$mid
        );
		$this->make_post_c($data);
	}
    
    /**
	 *未支付订单支付提交函数.   C 端用户
	 *@uses OrderRecord::alipay
	 */
     public static function make_post_c($data){
        $post_data = $data;
        $script_uri = substr($_SERVER['SCRIPT_URI'],0,strrpos($_SERVER['SCRIPT_URI'],'/'));
		$url=$script_uri.'/alipay/alipay_dev.php'; 
        $post_data = http_build_query($post_data);
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_POST, 1); 
		curl_setopt($ch, CURLOPT_HEADER, 0); 
		curl_setopt($ch, CURLOPT_URL,$url); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,0);
		return curl_exec($ch);
     }

}
?>